package cn.b.sky.form.controller;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.exception.InfoException;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.form.model.BusinessField;
import cn.b.sky.form.model.BusinessType;
import cn.b.sky.form.model.condition.BusinessTypeCondition;
import cn.b.sky.form.service.BusinessFieldService;
import cn.b.sky.form.service.BusinessTypeService;
import cn.b.sky.form.utils.BusinessTypeDefinitionUtils;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.user.service.RoleService;
import cn.b.sky.user.service.model.Role;
import cn.b.sky.user.service.model.RoleBusinessType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * <strong>Title : BusinessController.java<br></strong>
 * <strong>Package : cn.b.sky.flowable.controller<br></strong>
 * <strong>Description : </strong>业务类型操作控制器<br> 
 * <strong>Create on : 2016-09-27 下午05:56:14<br></strong>
 * <p>
 * @author JunLin.Yang<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping(value = "/workflowBusiness/*")
@Slf4j
public class BusinessController extends SecurityController {

  @Resource
  BusinessTypeService businessTypeService;

  @Resource
  BusinessFieldService businessFieldService;

  @Resource
  RoleService roleService;

  /**
   * 
   * <strong>Title : listBusinessTypesPageInfo<br></strong>
   * <strong>Description : </strong>根据查询条件查询业务类型分页信息<br> 
   * <strong>Create on : 2016-09-27 下午05:56:14<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param condition 业务类型查询条件
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "listBusinessTypesPageInfo")
  public String listBusinessTypesPageInfo(String navTabId, @ModelAttribute("condition") BusinessTypeCondition condition,
      Model model) {
    String siteCode = this.getSiteCode();

    model.addAttribute(NAVTABID, navTabId);

    // 添加SITECODE条件值并查询分页信息
    condition.setSiteCode(siteCode);

    if (StringUtils.isBlank(condition.getOrderField())) {
      //默认排序
      condition.setOrderField("createDateTime");
      condition.setOrderDirection("desc");
    }

    model.addAttribute("page", this.businessTypeService.selectBusinessTypePageByCondition(condition));

    return "workflow/businessType_list";
  }

  /**
   * 
   * <strong>Title : viewBusinessType<br></strong>
   * <strong>Description : </strong>根据主键查询业务类型对象<br> 
   * <strong>Create on : 2016-09-27 下午05:56:14<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param businessType 业务类型
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "viewBusinessType")
  public String viewBusinessType(String navTabId, String businessType, Model model) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("businessType",
        this.businessTypeService.getBusinessTypeAndFields(this.getSiteCode(), businessType));

    return "workflow/businessType_view";
  }

  /**
   * 
   * <strong>Title : toAddBusinessType<br></strong>
   * <strong>Description : </strong>新增业务类型信息前置事件<br> 
   * <strong>Create on : 2016-09-27 下午05:56:14<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "toAddBusinessType")
  public String toAddBusinessType(String navTabId, Model model) {

    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("siteCode", this.getSiteCode());
    return "workflow/businessType_add";
  }

  /**
   * 
   * <strong>Title : toEditBusinessType<br></strong>
   * <strong>Description : </strong>修改业务类型信息前置事件<br> 
   * <strong>Create on : 2016-09-27 下午05:56:14<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param businessType 业务类型
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "toEditBusinessType")
  public String toEditBusinessType(String navTabId, String businessType, Model model) {

    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("businessType",
        this.businessTypeService.getBusinessTypeAndFields(this.getSiteCode(), businessType));

    return "workflow/businessType_edit";
  }

  /**
   * 
   * <strong>Title : saveBusinessType<br></strong>
   * <strong>Description : </strong>新增或修改业务类型信息<br> 
   * <strong>Create on : 2016-09-27 下午05:56:14<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param businessType 业务类型
   * @param model 页面值对象
   * @return
   * DWZResult 操作结果
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "saveBusinessType")
  @ResponseBody
  public DWZResult saveBusinessType(String navTabId, BusinessType businessType, Model model) {
    if (null == businessType) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }

    businessType.setSiteCode(this.getSiteCode());
    businessType.setTableCreateFlag(SystemConstant.COMMON_STATUS_OFF);

    if (!this.businessTypeService.existBusinessTypeByPrimaryKey(businessType.getSiteCode(),
        businessType.getBusinessType())) {
      this.setCreateInfo(businessType);
      this.businessTypeService.insertBusinessTypeAndInitFields(businessType);
    } else {
      this.setModifyInfo(businessType);
      this.businessTypeService.updateBusinessType(businessType);
    }

    return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), navTabId, null, null, null);
  }

  /**
   * 
   * <strong>Title : deleteBusinessTypeBatch<br></strong>
   * <strong>Description : </strong>删除业务类型信息<br> 
   * <strong>Create on : 2016-09-27 下午05:56:14<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param model 页面值对象
   * @param request 页面请求对象
   * @return
   * DWZResult 操作结果
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "deleteBusinessTypeBatch")
  @ResponseBody
  public DWZResult deleteBusinessTypeBatch(String navTabId, Model model, HttpServletRequest request) {
    String businessTypeIds = request.getParameter("businessType_ids");
    if (StringUtils.isEmpty(businessTypeIds)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String siteCode = this.getSiteCode();
    String[] ress = businessTypeIds.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = this.businessTypeService.deleteBusinessTypeByPrimaryKey(siteCode, res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }
  }

  @RequestMapping("validateBusinessType")
  @ResponseBody
  public boolean validateBusinessType(String businessType, Model model) {
    if (!StringUtils.isEmpty(businessType)) {
      return !this.businessTypeService.existBusinessTypeByPrimaryKey(this.getSiteCode(), businessType.toUpperCase());
    }
    return false;
  }

  /**
  * 
  * <strong>Title : viewBusinessField<br></strong>
  * <strong>Description : </strong>根据主键查询业务字段对象<br> 
  * <strong>Create on : 2016-09-27 下午07:18:57<br></strong>
  * <p>
  * @param navTabId 页面导航ID
  * @param businessType 业务类型
  * @param businessField 业务字段
  * @param model 页面值对象
  * @return
  * String 页面地址
  * @throws 
  * @author JunLin.Yang<br>
  * @version <strong>v1.0.0</strong><br>
  * <br>
  * <strong>修改历史:</strong><br>
  * 修改人 | 修改日期 | 修改描述<br>
  * -------------------------------------------<br>
  * <br>
  * <br>
  */
  @RequestMapping(value = "viewBusinessField")
  public String viewBusinessField(String navTabId, String businessType, String businessField, Model model) {
    String siteCode = this.getSiteCode();

    model.addAttribute(NAVTABID, navTabId);

    model.addAttribute("businessField",
        this.businessFieldService.getBusinessFieldAndValues(siteCode, businessType, businessField));
    model.addAttribute("businessFieldDataTypes", BusinessTypeDefinitionUtils.getDataTypeList());
    model.addAttribute("businessFieldTypes", BusinessTypeDefinitionUtils.getFieldTypeList());

    return "workflow/businessField_view";
  }

  /**
   * 
   * <strong>Title : toAddBusinessField<br></strong>
   * <strong>Description : </strong>新增业务字段信息前置事件<br> 
   * <strong>Create on : 2016-09-27 下午07:18:57<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param businessType 业务类型
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "toAddBusinessField")
  public String toAddBusinessField(String navTabId, String businessType, Model model) {

    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("businessType", businessType);
    model.addAttribute("businessFieldDataTypes", BusinessTypeDefinitionUtils.getDataTypeList());
    model.addAttribute("businessFieldTypes", BusinessTypeDefinitionUtils.getFieldTypeList());

    return "workflow/businessField_add";
  }

  /**
   * 
   * <strong>Title : toEditBusinessField<br></strong>
   * <strong>Description : </strong>修改业务字段信息前置事件<br> 
   * <strong>Create on : 2016-09-27 下午07:18:57<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param businessType 业务类型
   * @param businessField 业务字段
   * @param model 页面值对象
   * @return
   * String 页面地址
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "toEditBusinessField")
  public String toEditBusinessField(String navTabId, String businessType, String businessField, Model model) {

    String siteCode = this.getSiteCode();

    BusinessField businessFieldData = this.businessFieldService.getBusinessFieldAndValues(siteCode, businessType,
        businessField);

    if (1 == businessFieldData.getSystemFieldFlag()) {
      //如果是系统内部字段则不允许编辑
      throw new InfoException(getImeViewMessageI18n(null, "noright.C"));
    }

    model.addAttribute(NAVTABID, navTabId);

    model.addAttribute("businessType", businessType);
    model.addAttribute("businessField", businessFieldData);
    model.addAttribute("businessFieldDataTypes", BusinessTypeDefinitionUtils.getDataTypeList());
    model.addAttribute("businessFieldTypes", BusinessTypeDefinitionUtils.getFieldTypeList());

    return "workflow/businessField_edit";
  }

  /**
   * 
   * <strong>Title : saveBusinessField<br></strong>
   * <strong>Description : </strong>新增或修改业务字段信息<br> 
   * <strong>Create on : 2016-09-27 下午07:18:57<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param businessField 业务字段
   * @param model 页面值对象
   * @return
   * DWZResult 操作结果
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "saveBusinessField")
  @ResponseBody
  public DWZResult saveBusinessField(String navTabId, BusinessField businessField, Model model) {
    if (null == businessField) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }

    if (1 == businessField.getSystemFieldFlag()) {
      //如果是系统内部字段则不允许编辑
      throw new InfoException(getImeViewMessageI18n(null, "noright.C"));
    }

    businessField.setSiteCode(this.getSiteCode());
    setCreateInfo(businessField);

    if (!this.businessFieldService.existBusinessFieldByPrimaryKey(businessField.getSiteCode(),
        businessField.getBusinessType(), businessField.getBusinessField())) {
      this.businessFieldService.insertBusinessFieldAndValues(businessField);
    } else {
      this.businessFieldService.updateBusinessFieldAndValues(businessField);
    }

    return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), navTabId, null, null, null);
  }

  /**
   * 
   * <strong>Title : deleteBusinessFieldBatch<br></strong>
   * <strong>Description : </strong>删除业务字段信息<br> 
   * <strong>Create on : 2016-09-27 下午07:18:57<br></strong>
   * <p>
   * @param navTabId 页面导航ID
   * @param businessType 业务类型
   * @param model 页面值对象
   * @param request 页面请求对象
   * @return
   * DWZResult 操作结果
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "deleteBusinessFieldBatch")
  @ResponseBody
  public DWZResult deleteBusinessFieldBatch(String navTabId, String businessType, Model model,
      HttpServletRequest request) {
    String businessField_ids = request.getParameter("businessField_ids");
    if (StringUtils.isEmpty(businessField_ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String siteCode = this.getSiteCode();
    String[] ress = businessField_ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    BusinessField businessFieldData = null;
    BatchJobReport report = null;
    for (String res : ress) {
      businessFieldData = this.businessFieldService.getBusinessFieldAndValues(siteCode, businessType, res);
      if (1 == businessFieldData.getSystemFieldFlag()) {
        //如果是系统字段
        report = new BatchJobReport(businessFieldData.getBusinessField(), getImeViewMessageI18n(null, "noright.C"),
            false);
      } else {
        report = this.businessFieldService.deleteBusinessFieldByPrimaryKey(siteCode, businessType, res);
      }

      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }
  }

  @RequestMapping("validateBusinessField")
  @ResponseBody
  public boolean validateBusinessField(String businessType, String businessField, Model model) {
    if (!StringUtils.isEmpty(businessType) && !StringUtils.isEmpty(businessField)) {
      return !this.businessFieldService.existBusinessFieldByPrimaryKey(this.getSiteCode(), businessType.toUpperCase(),
          businessField.toUpperCase());
    }
    return false;
  }

  /**
   * 
   * <strong>Title : doCreateOrUpdateBusinessTable<br></strong>
   * <strong>Description : </strong>生成或更新表<br> 
   * <strong>Create on : 2016年9月29日 下午2:51:00<br></strong>
   * <p>
   * @param navTabId
   * @param businessType 业务类型
   * @param model 数据模型
   * @return
   * DWZResult 操作结果
   * @throws 
   * @author JunLin.Yang<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "doCreateOrUpdateBusinessTable")
  @ResponseBody
  public DWZResult doCreateOrUpdateBusinessTable(String navTabId, String businessType, Model model) {

    if (StringUtils.isNotBlank(businessType)) {
      try {
        if (this.businessTypeService.doCreateOrUpdateBusinessTable(this.getSiteCode(), businessType)) {
          // 返回成功消息
          return navTabAjaxDone(navTabId, null, null, null,
              getImeViewMessageI18n(null, SystemConstant.DWZ_CODE_OK_MESSAGE), null);
        }
      } catch (Exception e) {
        if (null != e.getCause() && SQLException.class.isInstance(e.getCause())
            && e.getCause().getMessage().indexOf("ORA-00904") != -1) {
          return ajaxError(getImeViewMessageI18n(null, "tableCreateException.M"));
        }
        log.error("{}", e);
      }
    }

    return ajaxError(getImeViewMessageI18n(null, SystemConstant.DWZ_CODE_ERROR_MESSAGE));

  }

  @RequestMapping("editBusinessType")
  public String editBusinessType(Model model, String navTabId, String id) {
    List<RoleBusinessType> roleBusinessTypes = roleService.selectRoleBusinessTypeByRole(this.getSiteCode(), id);
    model.addAttribute("roleBusinessTypes", roleBusinessTypes);
    model.addAttribute("roleCode", id);
    model.addAttribute(NAVTABID, navTabId);
    return "workflow/RoleBusinessType_edit";
  }

  @RequestMapping("saveRoleBusinessType")
  @ResponseBody
  public DWZResult saveRoleBusinessType(String navTabId, Model model, Role role) {
    if (null == role) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    role.setSiteCode(this.getSiteCode());
    List<RoleBusinessType> list = role.getRoleBusinessTypes();
    if (list != null && list.size() > 0) {
      roleService.saveRoleBusinessType(role);
    }
    return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), navTabId, null, null, null);
  }
}
